package cumeo89.chii.client.entry.renderer;

import static cumeo89.chii.client.entry.Constants.*;

import com.google.gwt.xml.client.Node;

import cumeo89.chii.client.entry.AbstractRenderer;
import cumeo89.chii.client.entry.Renderer;
import cumeo89.chii.client.ui.ExtendedPanel;
import cumeo89.chii.client.ui.TrivialNamedPanel;
import cumeo89.chii.client.ui.TwoColumnPanel;
import cumeo89.chii.client.util.XMLUtil;

class TwoColumnListRenderer extends AbstractRenderer {

	private TrivialNamedPanel pnlContainer = new TrivialNamedPanel("div",
			new String[] { A_SUBLIST_TITLE });
	private TwoColumnPanel pnlContent = new TwoColumnPanel();

	public TwoColumnListRenderer() {
		pnlContainer.add(pnlContent);
		initWidget(pnlContainer);
	}

	@Override
	protected ExtendedPanel getChildContainer() {
		return pnlContent;
	}

	@Override
	public void addRenderer(Renderer child) {
		// TODO Auto-generated method stub
		super.addRenderer(child);
	}

	@Override
	public Node getLeftNode(Node child) {
		return getHorizontallyNextNode(child);
	}

	@Override
	public Node getRightNode(Node child) {
		return getHorizontallyNextNode(child);
	}

	private Node getHorizontallyNextNode(Node child) {
		int i = XMLUtil.getIndexOf(child, getRenderedNode());
		int j = i + (getRenderedNode().getChildNodes().getLength() + 1) / 2;
		if (j % 2 != 0 && j == getRenderedNode().getChildNodes().getLength()) {
			return child;
		}
		if (j >= getRenderedNode().getChildNodes().getLength()) {
			j -= (getRenderedNode().getChildNodes().getLength() + 1) / 2;
		}
		return getRenderedNode().getChildNodes().item(j);
	}

}
